//
//  LXOModel.m
//  runtime字典Model
//
//  Created by webplus on 17/9/1.
//  Copyright © 2017年 sanyi. All rights reserved.
//

#import "LXOModel.h"
#import <objc/runtime.h>

@implementation LXOModel


- (id)initWithDictionary:(NSDictionary *)dict{
    if (self = [super init]) {
        [self reflectDataFromDictionary:dict];
    }
    return self;
}

- (void)reflectDataFromDictionary:(NSDictionary *)dict{
    unsigned int useCount = 0,outCount;
    
    Ivar *vars = class_copyIvarList([self class], &outCount);
    for (int i = 0; i<outCount; i++) {
        Ivar var = vars[i];
        NSString *varName = [NSString stringWithUTF8String:ivar_getName(var)];
        id varValue = [self valueForKey:varName];
        if ([[dict allKeys] containsObject:varName]) {
            varValue = [dict objectForKey:varName];
            useCount ++;
        }else{
            NSString *temp_varName = [self removeFirstUnderlined:varName];
            if ([[dict allKeys] containsObject:temp_varName]) {
                varValue = [dict objectForKey:temp_varName];
               
                useCount ++;
            }
        }
        [self setValue:varValue forKey:varName];
    }
    NSLog(@"属性个数为：%d",useCount);
}

- (NSDictionary *)convertToDictionary{
     NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
    for (NSString *key in [self propertyKeys]) {
        id value = [self valueForKey:key];
        [dict setObject:value forKey:key];
    }
    return dict;
}




-(NSString *)removeFirstUnderlined:(NSString *)str{
    if ([[str substringToIndex:1] isEqual:@"_"]) {
        return [str substringFromIndex:1];
    }
    return str;
}

- (NSArray *)propertyKeys{
    unsigned int outCount,i;
    objc_property_t *properties = class_copyPropertyList([self class], &outCount);
    NSMutableArray *keys = [[NSMutableArray alloc]initWithCapacity:outCount];
    for (i = 0; i<outCount; i++) {
        objc_property_t property = properties[i];
        NSString *propertyName = [[NSString alloc]initWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
        [keys addObject:propertyName];
    }
    
    return keys;
}




@end
